/*
 * @Description: 回退的一些方法
 */
import { useSummaryCommentWithOut } from '@/store/modules/summary/comment';
import { useBaseInfoWithOut } from '@/store/modules/base-info';
import globalData from '@/plugins/data';
import globalMethods from '@/plugins/methods';
import api from '@/api';
import ChooseAttitude from './components/chooseAttitude.vue';
import ChooseFlow from './components/chooseFlow.vue';
//关闭窗口
import closeWindow from '@/helper/close';
import { getFormData, getCollaborationData, getWorkflowData } from '../continue-submit/helper';
import {useTemplateWithOut} from "@/store/modules/template";
import {getWorkflowTransParams} from "@/helper/workflow-helper";
import {APPLICATIONCATEGORYE} from "@/utils/const";
import errHandle from "@/handles/common/err-handle";
const useSummaryComment = useSummaryCommentWithOut();
const useBaseInfo = useBaseInfoWithOut();

const useTemplate = useTemplateWithOut();

const FULL_OPTION_LIST = [
  {
    name: $.i18n('collaboration.appointStepBack.ProcessTheHeavy'),
    tip: $.i18n('workflow.special.stepback.label15'),
    value: 0
  },
  {
    name: $.i18n('workflow.special.stepback.label7'),
    tip: $.i18n('workflow.special.stepback.label5'),
    value: 1
  }
];

/**
 * @description: 拼装回退接口数据并提交
 * @param {Object}btn 按钮数据
 * @param {Function}updateParams 修改数据函数
 * @param successFn 执行成功后回调
 * @return {*}
 */

export async function submitReturn(btn, updateParams , successFn = () => {}) {
  useBaseInfo.setIsHideGlobalLoading(false);
  try {
    //校验
    if (!useBaseInfo.validateAttachmentUploading()) {
      useBaseInfo.setIsHideGlobalLoading(true);
      return Promise.resolve();
    }
    //获取协同数据
    const collaborationDealParamData = getCollaborationData(btn);

    //获取表单数据
    const formParamData = await getFormData(btn.handle, false);
    if (!formParamData) {
      useBaseInfo.setIsHideGlobalLoading(true);
      return Promise.resolve();
    }

    //获取工作流数据
    const workflowParamData = getWorkflowData(formParamData);
    
    //三方扩展数据
    const thirdpartParamData = {
      beforeEventBO: {},
      data: [],
      thirdPartyContext: useBaseInfo.thirdPartyContext
    };

    const params = {
      formParamData: { data: formParamData },
      workflowParamData,
      collaborationDealParamData,
      thirdpartParamData
    };

    //提供提交前修改数据功能
    if (updateParams) {
      updateParams(params);
    }
    let editAttOrContent = window.isEditAttOrContent;
    if (editAttOrContent&&editAttOrContent!==0 ){
      const fnx = useTemplate.zwIframe.contentWindow;
      //0 ： 没有做修改, 1:修改了正文   2：修改了附件 3 ： 修改了正文和附件
      let cLabel=$.i18n("common.toolbar.content.label");
      if (editAttOrContent === 2){
        cLabel = $.i18n("common.attachment.label");
      }else if(editAttOrContent === 3) {
        cLabel = $.i18n("collaboration.label.contentAndAtt.js");
      }
      //弹窗确认是否需要保存正文,保存失败会触发reject异常
      await (new Promise((resolve, reject) => {
        this.$confirm({
          title: this.$i18n('common.system.hint.label'),
          content: $.i18n('collaboration.label.confirm.saveAttOrContent.js', cLabel),
          closable: true,
          onCancel: () => {
            reject();
          },
          onOk: () => {
            resolve();
          },
        });
      }).then(()=> new Promise((resolve, reject)=>{
        const {id} = useBaseInfo.baseInfo.businessData.summary;
        fnx.contentAPI.submit({
          checkNull: false,
          mainbodyDomains: [],
          needCheckRepeatData: false,
          needCheckRule: false,
          needSn: false,
          needSubmit: true,
          noCheckFormContent:true,
          optType: btn.handle,
          summaryId: id,
          failed: () => reject(),
          success: () => resolve(),
        })
      })))
    }
    
    
    
    console.log('回退数据', params.collaborationDealParamData.submitCode, params);
    const {data: result} = await api.summarySubmitReturn(params) || {};
    const {passed, app, data} = result || {};
    if (!passed && data) {
      const {data: errorObj} = data[app];
      if (errorObj) {
        const {weakBlock} = errorObj;
          await new Promise(resolve => {
            errHandle(result,
              async () => {
                //2、放在回调里面去执行再次回退，有三方Listener决定是否提交通过
                await submitReturn.call(this, btn, (params) => {
                  updateParams.call(this, params);
                  params.workflowParamData.weekSubmit = weakBlock;
                }, () => {
                  successFn.call(this)
                });
                resolve(true);
              },
              () => resolve(false),
            )
          });
          return Promise.resolve();
      }
    }

    this.$message.success({
      content: this.$i18n('collaboration.deal.success.title'),
      onClose: () => {
        useBaseInfo.setIsHideGlobalLoading();
      }
    });
    console.log('window.close');
    successFn();
    closeWindow();
  } catch (e) {
    console.log('回退错误', e);
    useBaseInfo.setIsHideGlobalLoading();
    //环形分支就清空数据
    if (btn.isCircleBack) {
      window.removeWorkflowMatchResultCache();
    }
  }
}

/**
 * @description: 回退发起人。选择处理后。直接提交给我、流程重走
 * @param {Number}type  0:流程重走、1:提交给我、2:回退人自选
 * @return {*}
 */
export function returnSender(type, btn) {
  //完整选项
  let options = FULL_OPTION_LIST.slice();
  options[0].isDisabled = !btn.canRego; //置灰。目前发现是在指定回退回来的时候

  //根据类型不同删减
  if (type !== 2) {
    options = options.splice(type, 1);
  }

  let submitStyle = options[options[0].isDisabled ? 1 : 0].value;
  this.$confirm({
    title: this.$i18n('common.workflow.specialback.label'),
    // h 参数需保留，渲染需要该参数
    // eslint-disable-next-line no-unused-vars
    content: h => (
      <ChooseFlow
        name={useBaseInfo.baseInfo.businessData.affair.affairMemberName}
        options={options}
        v-model={submitStyle}
      />
    ),
    closable: true,
    width: 750,
    onOk: () => {
      const appointStepBack = {
        theStepBackNodeId: 'start',
        submitStyle
      };
      chooseAttitude.call(this, btn, {
        appointStepBack
      });
    }
  });
}

/**
 * @description:回退操作,选择态度haveRead: 已阅/agree: 同意/disagree: 不同意
 * @param {String} handle 回退-return 终止-terminate 撤销-cancel
 * @param {String} label 当前执行的操作（按钮）名
 * @param {Object} mergeColData 需要合并进协同的数据
 * @param closeFn 关闭回调
 * @return {*}
 */
export function chooseAttitude(btn, mergeColData, closeFn = () => {}) {
  //校验
  if (!useBaseInfo.validateAttachmentUploading()) {
    return closeFn();
  }
  const { handle, label, attitude: btnAttitude } = btn;
  //如果直接是不同意了(封装的或者选择的),就弹出提示。不用选了
  const isDisagree = btnAttitude
    ? btnAttitude === 'disagree'
    : useSummaryComment.attitude === 'disagree';
  //选项值
  let attitude = 'disagree';
  this.$confirm({
    title: $.i18n('common.system.hint.label'),
    content:
      //节点权限为“发起人填写”，就没有态度
      isDisagree || !useSummaryComment.attitudeList.length
        ? $.i18n('collaboration.check.opinion.action', label)
        // h 参数需保留，渲染需要该参数
        // eslint-disable-next-line no-unused-vars
        : h => (
            <ChooseAttitude
              label={label}
              type={handle}
              options={useSummaryComment.attitudeList.map((d) => ({
                label: d.subject,
                value: d.code
              }))}
              v-model={attitude}
            />
          ),
    closable: true,
    width: 500,
    onOk: () => {
      //调接口
      //加上处理意见
      submitReturn.call(this, btn, (params) => {
        //态度有变动
        if (attitude !== useSummaryComment.attitude) {
          let find = useSummaryComment.attitudeList.find(
            (d) => d.code === attitude
          );
          //没有默认的态度
          if (!find) {
            find = {
              code: attitude
            }
          }
          params.collaborationDealParamData.comment.attitude = find;
        }
        //有需要合并的就合并
        if (mergeColData) {
          Object.assign(params.collaborationDealParamData, mergeColData);
        }
      },closeFn).then(()=>{
        closeFn();
        useBaseInfo.setIsHideGlobalLoading();
      });
      // this.$message.success(`${label}成功！${value}`);
    },
    onClose:closeFn,
    onCancel:closeFn,
  });
}

/**
 * @description: 指定回退
 * @param {*}
 * @return {*}
 */
//指定回退
export function specifiesReturn(btn) {
  if (!useBaseInfo.checkSecret()) return;
  const { returnDetailData } = btn;
  //type:0:流程重走、1:提交给我、2:回退人自选。如果是自定义按钮就看配置的是什么否则（就是指定回退）就是submitStyle字段
  const type = returnDetailData ? +returnDetailData.split('|')[1] : btn.submitStyle;
  const baseInfo = useBaseInfo.baseInfo;
  const { businessData } = baseInfo;
  const { processId, caseId } = businessData.summary;
  //生成基础URL
  let url = `${
    globalData.ctxPath
  }/workflow/designer.do?method=showDiagram&v=${`${globalMethods.getSecurityByUserId()}`}&isDebugger=false&scene=6&isModalDialog=true&processId=${processId}&caseId=${caseId}&currentNodeId=${
    businessData.affair.activityId
  }&permissionAccountId=&appName=collaboration&isTemplate=false&NPS=default&SPK=&stepBackToNodeId=`;
  
  //根据配置显示选项
  if (type === 2 || type === 0) {
    url += '&showReGo=true';
  }

  if (type === 2 || type === 1) {
    url += '&showToMe=true';
  }
  //预制的节点权限为null，要走全选的情况
  if (!type && type !== 0) {
    url += '&showToMe=true&showReGo=true';
  }

  const dialog = globalMethods.fullDialog({
    id: 'workflow_dialog_workflowDesigner_Id',
    title: this.$i18n('common.workflow.specialback.label'),
    bodyStyle:'padding:0',
    url,
    bottomHTML: `<span >${this.$i18n('workflow.trace.msg')}</span>`,
    transParams: getWorkflowTransParams(),
    minParam: {
      show: false
    },
    maxParam: {
      show: false
    },
    notCopyReturnValue: true,
    onCancel() {
      dialog.close();
    },
    onConfirm: () => {
      //one true
      //two 当前选中人员的id。如果是第一个就是start
      //three 重走是0 提交给我是1
      //four 当前选中人员的名字
      //five 0 （按接口文档来分析就当是是否环形分支）
      const [one, theStepBackNodeId, submitStyle, four, isCircleBack] = dialog.getValue({
        innerButtonId: 'stepback_ok'
      });
      console.log(one, theStepBackNodeId, submitStyle, four, isCircleBack);
      if (one){
        chooseAttitude.call(this, btn, {
            appointStepBack: {
              theStepBackNodeId,
              submitStyle,
              isCircleBack
            }
          },
          () => {
            dialog.close();
            useBaseInfo.setIsHideGlobalLoading();
          });
      }else {
        globalMethods.warning({
          title: globalMethods.i18n('common.system.hint.label'),
          content: globalMethods.i18n('workflow.special.stepback.label9')
        });
      }
    }
  });
}
